//app.js

App({

   data: {
      innerAudioContext: wx.createInnerAudioContext(),
      mp3a: 'https://realyawwj.oss-cn-hangzhou.aliyuncs.com/more/musica.mp3',
      mp3b:'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46',
      cutMusic: false,
      musicLine: false,
   },
   /**
    * 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
    */
   onLaunch: function () {
      this.data.innerAudioContext.src = this.data.mp3b;
      this.data.innerAudioContext.volume = 0.1;
      this.data.innerAudioContext.autoplay = false;
      this.data.innerAudioContext.startTime = 0;
      this.data.innerAudioContext.loop = true;
      this.data.innerAudioContext.obeyMuteSwitch = false;
   },

   /**
    * 当小程序启动，或从后台进入前台显示，会触发 onShow
    */
   onShow: function (options) {
      console.log('当小程序启动，或从后台进入前台显示，会触发 onShow')
      console.log(this.data.cutMusic)
      console.log(this.data.musicLine)
      if (this.data.musicLine) {
         this.data.cutMusic = true;
      }
      else {
         this.data.cutMusic = false;
      }
      this.startPlayBackgroundMusic();
   },

   /**
    * 当小程序从前台进入后台，会触发 onHide
    */
   onHide: function () {
      console.log('当小程序从前台进入后台，会触发 onHide')
      console.log(this.data.cutMusic)
      console.log(this.data.musicLine)
      this.data.cutMusic = true;
      this.stopPlayBackgroundMusic();
   },

   /**
    * 关闭背景音乐
    */
   stopPlayBackgroundMusic() {
      console.log(this.data.cutMusic)
      console.log(this.data.musicLine)
      if (this.data.cutMusic) {
         this.data.innerAudioContext.pause();
         this.data.innerAudioContext.onPause(() => {
            console.log('音频被被暂停')
         })
      }
   },

   /**
    * 播放背景音乐
    */
   startPlayBackgroundMusic() {
      console.log(this.data.cutMusic)
      console.log(this.data.musicLine)
      if (!this.data.cutMusic) {
         console.log('准备播放')
         this.data.innerAudioContext.play(); //接着上次播放音频
         this.data.innerAudioContext.onCanplay(() => {
            console.log('音频进入可以播放状态')
            if (!this.data.cutMusic){
               this.data.innerAudioContext.play(); //接着上次播放音频
               this.data.innerAudioContext.onPlay(() => {
                  console.log('音频播放中')
                  this.data.innerAudioContext.onEnded(() => {
                     console.log('自然播放结束')
                  })
               })
            }
         })
      }
   },

   /**
    * 当小程序发生脚本错误，或者 api 调用失败时，会触发 onError 并带上错误信息
    */
   onError: function (msg) {

   }
})
